import { Link } from 'react-router-dom';
import {
  useDispatch,
  useSelector
} from "react-redux";
import {clearCart, getCart} from "./cartSlice.js";
import CartItem from "./CartItem.jsx";
import EmptyCart from "./EmptyCart.jsx";


function Cart() {
  const username = useSelector((state) => state.user.username);
  const cart = useSelector(getCart);
  const dispatch = useDispatch();

  if(!cart.length) return <EmptyCart />

  return (
    <div className={"px-4 py-3"}>
      <Link to="/menu">&larr; Back to menu</Link>

      <h2 className={"mt-7 text-xl font-semibold"}>Your cart, { username }</h2>

      <ul className={"mt-3 divide-y divide-stone-200 border-b"}>
        {
          cart.map((item) =>(
              <CartItem item={item} key={item.id} />
          ))
        }
      </ul>

      <div className={"mt-6 space-x-2"}>
        <Link to="/order/new">
          Order pizzas
        </Link>
        <button type={"secondary"} onClick={()=>dispatch(clearCart())}>
          Clear cart
        </button>
      </div>
    </div>
  );
}

export default Cart;
